package com.ryf.maven.servlet.student;

import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;
import com.ryf.maven.dao.StudentDao;
import com.ryf.maven.entity.BaseResponse;
import com.ryf.maven.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Description
 * @ClassName StudentAllServlet
 * @Author L-Cohen
 * @date 2020.12.01 20:34
 */
@WebServlet(urlPatterns = "/stu/all/")
public class StudentAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        BaseResponse<List<Student>> response = new BaseResponse<List<Student>>();
        BaseResponse<Student> response1 = new BaseResponse<Student>();
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String stuNo = req.getParameter("stuNo");

        Student student1 = StudentDao.getStuByStuNo(stuNo);
        if (student1 != null){
            response1.setData(student1);

            Gson gson = new Gson();
            String json = gson.toJson(response1);
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.print(json);
            out.flush();
        }else {
            List<Student> student = StudentDao.getStudent(StringUtils.isNullOrEmpty(page) ? 1 : Integer.parseInt(page),
                    StringUtils.isNullOrEmpty(limit) ? 10 : Integer.parseInt(limit));

            int rows = StudentDao.getCount();
            response.setCode(200);
            response.setCount(rows);
            response.setMsg("请求成功");
            response.setData(student);

            Gson gson = new Gson();
            String json = gson.toJson(response);
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.print(json);
            out.flush();
        }

    }
}
